package com.module.base.widget.recyclerview;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.module.base.utils.ParentDisableUtils;

/**
 * 横向嵌套竖向，滑动冲突问题，如
 * ViewPage2 嵌套 RecyclerView
 * 默认不处理跟普通RecyclerView一样，
 * 调用setNestDeal打开
 * */
public class NestVerticalRecyclerView extends RecyclerView {

    private int lastX = -1;
    private int lastY = -1;
    boolean isHorizontal;
    private boolean isNestDeal;//是否开启嵌套处理,遇到类似ViewPage2 嵌套 RecyclerView再打开，能减少代码判断就减少。

    public NestVerticalRecyclerView(Context context) {
        super(context);
    }

    public NestVerticalRecyclerView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public NestVerticalRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (!isNestDeal){
            return super.dispatchTouchEvent(ev);
        }
        int dealtX = 0;
        int dealtY = 0;

        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                isHorizontal = false;
                lastX = (int) ev.getRawX();
                lastY = (int) ev.getRawY();
                break;
            case MotionEvent.ACTION_MOVE:
                dealtX = Math.abs((int) ev.getRawX() - lastX);
                dealtY = Math.abs((int) ev.getRawY() - lastY);
                if (isHorizontal) {
                    setDisable(false);
                } else if (dealtX > dealtY) {
                    setDisable(false);
                    isHorizontal = true;
                } else {
                    setDisable(true);
                }
                lastX = (int) ev.getRawX();
                lastY = (int) ev.getRawY();
                break;
            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_UP:
                setDisable(false);
                break;
        }
        return super.dispatchTouchEvent(ev);
    }


    public void setDisable(boolean disable) {
        //屏蔽横向父类
        ParentDisableUtils.setHorizontalParentDisable(getParent(), disable);
    }

    public void setNestDeal(boolean nestDeal) {
        isNestDeal = nestDeal;
    }
}
